//
//  MDataListViewController.m
//  Gunz
//
//  Created by Joggy on 16/8/17.
//  Copyright © 2016年 NUPT. All rights reserved.
//

#import "MDataListViewController.h"
#import "MDataDetailLightViewController.h"
#import "MDataDetailQuesViewController.h"
#import "MDataDetailAudioViewController.h"
#import "MDataDetailVideoViewController.h"
#import "MDataDetailImageViewController.h"
#import "AudioPlayViewController.h"

@interface MDataListViewController ()<UITableViewDelegate, UITableViewDataSource> {
    
    UITableView *table;
    NSMutableArray *data;
    NSString *currentBasePath;
    NSInteger selectedIndex;
}

@end

@implementation MDataListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareForNav];
    [self prepareForLayout];
    [self collectData];
    
}

- (void)prepareForNav {
    [super prepareForNav];
    self.title = @"数据列表";
    //导航左按键
    UIImage *image = [UIImage imageNamed:@"all_back"];
    UIButton *leftBarButton = [UIButton buttonWithType:UIButtonTypeSystem];
    leftBarButton.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    leftBarButton.layer.position = CGPointMake(22, 22);
    [leftBarButton setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    [leftBarButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBarButton];
    if(_isPresent) {
        NSLog(@"%@", @"present");
        UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
        rightButton.frame = CGRectMake(0, 0, 44, 44);
        [rightButton setAttributedTitle:[[NSAttributedString alloc] initWithString:@"选择" attributes:@{NSForegroundColorAttributeName: CUSTOM_GREEN}] forState:UIControlStateNormal];
        [rightButton addTarget:self action:@selector(conformSelect) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    }
}

- (void)prepareForLayout {
    [super prepareForLayout];
    table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight - 64) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    table.backgroundColor = [UIColor clearColor];
    table.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 10)];
    table.showsVerticalScrollIndicator = false;
    table.separatorStyle = UITableViewCellSelectionStyleBlue;
    table.separatorColor = [UIColor colorWithRed:0.85 green:0.85 blue:0.85 alpha:1];
    [table registerClass:[UITableViewCell class] forCellReuseIdentifier:@"MDataListCell"];
    [self.view addSubview:table];
}

- (void)collectData {
    NSArray *pathList = [GZConst getDataPathList];
    NSFileManager *manager = [NSFileManager defaultManager];
    currentBasePath = [NSString stringWithFormat:@"%@/%@", documentBasePath, pathList[_dataType]];
    data = (NSMutableArray*)[manager subpathsAtPath:currentBasePath];
    NSLog(@"%@", data);
    [table reloadData];
}

- (void)conformSelect {
    if(selectedIndex < 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请选择数据" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:alert animated:true completion:nil];
    }
    else {
        [self dismissViewControllerAnimated:true completion:^{
            NSDictionary *userInfo = @{@"dataPath": [NSString stringWithFormat:@"%@/%@", currentBasePath, data[selectedIndex]]};
            [[NSNotificationCenter defaultCenter] postNotificationName:GZPathOfSelectedDataNotification object:nil userInfo:userInfo];
        }];
    }
}

- (void)back {
    [self.navigationController popViewControllerAnimated:true];
}

#pragma 代理方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(!_isPresent) {
        [tableView deselectRowAtIndexPath:indexPath animated:true];
        
        switch (_dataType) {
            case GZDataTypeLight: {
                MDataDetailLightViewController *lightDetail = [[MDataDetailLightViewController alloc] init];
                lightDetail.dataPath = [NSString stringWithFormat:@"%@/%@", currentBasePath, data[indexPath.row]];
                [self.navigationController pushViewController:lightDetail animated:true];
            }
                break;
            case GZDataTypeQuestion: {
                MDataDetailQuesViewController *quesDetail = [[MDataDetailQuesViewController alloc] init];
                quesDetail.dataPath = [NSString stringWithFormat:@"%@/%@", currentBasePath, data[indexPath.row]];
                [self.navigationController pushViewController:quesDetail animated:true];
            }
                break;
            case GZDataTypeAudio: {
                MDataDetailAudioViewController *audioDetail = [[MDataDetailAudioViewController alloc] init];
                audioDetail.dataPath = [NSString stringWithFormat:@"%@/%@", currentBasePath, data[indexPath.row]];
                [self.navigationController pushViewController:audioDetail animated:true];
            }
                break;
            case GZDataTypeVideo: {
                MDataDetailVideoViewController *videoDetail = [[MDataDetailVideoViewController alloc] init];
                videoDetail.dataPath = [NSString stringWithFormat:@"%@/%@", currentBasePath, data[indexPath.row]];
                [self.navigationController pushViewController:videoDetail animated:true];
            }
                break;
            case GZDataTypeImage: {
                MDataDetailImageViewController *imageDetail = [[MDataDetailImageViewController alloc] init];
                imageDetail.dataPath = [NSString stringWithFormat:@"%@/%@", currentBasePath, data[indexPath.row]];
                [self.navigationController pushViewController:imageDetail animated:true];
            }
                break;
            default:
                break;
        }
        
    }
    selectedIndex = indexPath.row;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 47;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return data.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 20;
}

-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, screenWidth, 20)];
    v.backgroundColor = [UIColor clearColor];
    return v;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MDataListCell"];
    cell.backgroundColor = [UIColor colorWithRed:0.9765 green:0.9765 blue:0.9843 alpha:1];
    cell.textLabel.text = data[indexPath.row];
    cell.textLabel.textColor = TEXT_TITLE_COLOR;
    return cell;
}

#pragma mark -- 左划删除

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    if(_isPresent) {
        return false;
    }
    else {
        return true;
    }
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [tableView setEditing:false animated:true];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认删除？" message:nil preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSFileManager *manager = [NSFileManager defaultManager];
            [manager removeItemAtPath:[NSString stringWithFormat:@"%@/%@", currentBasePath, data[indexPath.row]] error:nil];
            [data removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        }]];
        [self presentViewController:alert animated:true completion:nil];
    }];
    UITableViewRowAction *reNameAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"重命名" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [tableView setEditing:false animated:true];
//        NSFileManager *manager = [NSFileManager defaultManager];
        
        NSLog(@"重命名");
    }];
    
    return @[deleteAction, reNameAction];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
